package org.mspring.mlog.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.mspring.mlog.dao.ArticleDao;
import org.mspring.mlog.dao.CommentDao;
import org.mspring.mlog.duoshuo.DuoshuoService;
import org.mspring.mlog.duoshuo.ImportRequest;
import org.mspring.mlog.duoshuo.sync.CreateMeta;
import org.mspring.mlog.duoshuo.sync.SyncAction;
import org.mspring.mlog.duoshuo.sync.SyncHandler;
import org.mspring.mlog.duoshuo.sync.SyncResponse;
import org.mspring.mlog.entity.Article;
import org.mspring.mlog.entity.Comment;
import org.mspring.mlog.entity.em.ArticleStatus;
import org.mspring.mlog.entity.em.CommentStatus;
import org.mspring.nbee.common.utils.CollectionUtils;
import org.mspring.nbee.db.dao.sql.builder.part.condition.SqlCondition;
import org.mspring.nbee.db.dao.sql.pager.PageResult;
import org.mspring.nbee.db.dao.sql.pager.Pager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Gao Youbo
 * @since 2015-01-03 14:38:26
 */
@Service
public class CommentService {

    private static final Logger LOG = LoggerFactory.getLogger(CommentService.class);

    private CommentDao commentDao;
    private ArticleDao articleDao;
    private DuoshuoService duoshuoService;

    public Comment findById(long id) {
        return commentDao.findById(id);
    }

    public PageResult<Comment> list(List<SqlCondition> conditions, Pager pager) {
        return commentDao.listPage(conditions, pager);
    }

    public List<Comment> listByArticle(long articleId) {
        return commentDao.listByArticle(articleId);
    }

    /**
     * 将评论导入到多说
     */
    public void importToDuoshuo() {
        List<Article> articleList = articleDao.listAll();
        if (CollectionUtils.isEmpty(articleList)) {
            return;
        }
        for (Article article : articleList) {
            if (article.getStatus() != ArticleStatus.NORMAL) {
                continue;
            }
            List<Comment> commentList = commentDao.listByArticle(article.getId());
            if (CollectionUtils.isEmpty(commentList)) {
                continue;
            }
            List<ImportRequest.Post> posts = new ArrayList<>();
            for (Comment comment : commentList) {
                ImportRequest.Post post = new ImportRequest.Post();
                post.setPostKey(String.valueOf(comment.getId()));
                post.setThreadKey(String.valueOf(comment.getArticleId()));
                post.setMessage(comment.getContent());
                post.setParentKey(String.valueOf(comment.getReplyId()));
                post.setAuthorName(comment.getAuthorName());
                post.setAuthorEmail(comment.getAuthorEmail());
                post.setAuthorUrl(comment.getAuthorUrl());
                post.setIp(comment.getIp());
                post.setAgent(comment.getAgent());
                post.setCreatedAt(DateFormatUtils.format(comment.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                posts.add(post);
            }
            duoshuoService.importComment(posts);
        }
    }

    /**
     * 从多说同步到本地
     */
    @Transactional
    public void syncFromDuoshuo() {
        duoshuoService.sync(new SyncHandler() {
            @Override
            public void handle(SyncResponse response) throws Exception {
                if (response.getAction() == SyncAction.CREATE) {
                    CreateMeta meta = CreateMeta.fromJsonString(response.getMeta());
                    Comment comment = new Comment();
                    comment.setDuoshuoCommentId(meta.getPostId());
                    comment.setArticleId(Long.valueOf(meta.getThreadKey()));
                    comment.setContent(meta.getMessage());
                    comment.setAuthorName(meta.getAuthorName());
                    comment.setAuthorEmail(meta.getAuthorEmail());
                    comment.setAuthorUrl(meta.getAuthorUrl());
                    comment.setIp(meta.getIp());
                    comment.setCreateTime(meta.getCreatedAt());
                    if (meta.getParentId() > 0) {
                        Comment parent = commentDao.findByDuoshuoCommentId(meta.getParentId());
                        if (parent != null) {
                            comment.setReplyId(parent.getId());
                        } else {
                            LOG.warn("#1未找到多说对应评论, duoshuoCommentId={}", meta.getParentId());
                        }
                    }
                    if (StringUtils.equalsIgnoreCase(meta.getStatus(), "pending")) {
                        comment.setStatus(CommentStatus.PENDING);
                    } else if (StringUtils.equalsIgnoreCase(meta.getStatus(), "spam")) {
                        comment.setStatus(CommentStatus.SPAM);
                    } else {
                        comment.setStatus(CommentStatus.APPROVED);
                    }
                    insert(comment);
                } else {
                    JSONArray meta = JSON.parseArray(response.getMeta());
                    for (int i = 0; i < meta.size(); i++) {
                        long duoshuoCommentId = meta.getLongValue(i);
                        Comment comment = commentDao.findByDuoshuoCommentId(duoshuoCommentId);
                        if (comment != null) {
                            if (response.getAction() == SyncAction.APPROVE) {
                                comment.setStatus(CommentStatus.APPROVED);
                                update(comment);
                            } else if (response.getAction() == SyncAction.SPAM) {
                                comment.setStatus(CommentStatus.SPAM);
                                update(comment);
                            } else if (response.getAction() == SyncAction.DELETE) {
                                comment.setStatus(CommentStatus.DELEtED);
                                update(comment);
                            } else if (response.getAction() == SyncAction.DELETE_FOREVER) {
                                deleteById(comment.getId());
                            }
                        } else {
                            LOG.warn("#2未找到多说对应评论,duoshuoCommentId={}", duoshuoCommentId);
                        }
                    }
                }
            }
        });
    }

    @Transactional
    public boolean insert(Comment comment) {
        return commentDao.insert(comment);
    }

    @Transactional
    public boolean update(Comment comment) {
        return commentDao.update(comment);
    }

    @Transactional
    public boolean deleteById(long id) {
        Comment comment = findById(id);
        if (comment == null) {
            return true;
        }
        comment.setStatus(CommentStatus.DELEtED);
        return commentDao.update(comment);
    }

    /**
     * 标记为垃圾评论
     *
     * @param id
     * @return
     */
    @Transactional
    public boolean spam(long id) {
        Comment comment = findById(id);
        if (comment == null) {
            return true;
        }
        comment.setStatus(CommentStatus.SPAM);
        return commentDao.update(comment);
    }

    /**
     * 恢复正常
     *
     * @param id
     * @return
     */
    @Transactional
    public boolean recover(long id) {
        Comment comment = findById(id);
        if (comment == null) {
            return true;
        }
        comment.setStatus(CommentStatus.APPROVED);
        return commentDao.update(comment);
    }

    @Autowired
    public void setCommentDao(CommentDao commentDao) {
        this.commentDao = commentDao;
    }

    @Autowired
    public void setArticleDao(ArticleDao articleDao) {
        this.articleDao = articleDao;
    }

    @Autowired
    public void setDuoshuoService(DuoshuoService duoshuoService) {
        this.duoshuoService = duoshuoService;
    }
}